function set_tunn_cookie(name, value, days)
{
    if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+escape(value)+expires;
}

function common_call(obj, cb, ecb) { /*cb,ecb是预留的处理函数,cb表示请求成功后的处理函数，ecb表示请求失败后的处理函数*/
    var sn=$('#dev_sn').val();  /*申明变量sn，sn=前端ID=dev_sn的值*/
    $.ajax({
        dataType: 'json',
        url: '/api/'+obj+'/'+sn, /* http://0.0.0.0/api/online/7051d2 */
        success: function (resp) {
			if (cb!=null) //如果处理函数不为空，则处理返回的数据
				cb(resp);
			else
				$("#result_msg").text(resp.val); //没有处理函数，直接将返回数据赋值给前端的ID=result_msg的值
        }, error: function (xhr) {
            console.log("Error on ajax call " + xhr);
			if (ecb!=null)
				ecb(xhr);
        }
    })
}

function cmd_call(obj, cb, ecb) {
    var sn=$('#dev_sn').val();
    var cmd=$('#cmd').val();
    $.ajax({
        dataType: 'json',
        url: '/api/'+obj+'/'+sn+'/'+cmd+'/',
        success: function (resp) {
			if (cb!=null)
				cb(resp);
			else
				$("#result_msg").text(resp.val);
        }, error: function (xhr) {
            console.log("Error on ajax call " + xhr);
			if (ecb!=null)
				ecb(xhr);
        }
    })
}

function server_call(obj, cb, ecb) {
    var sn=$('#dev_sn').val();
	var server=$('#server').val();
	var tcp=$('#tcp').val();
	var udp=$('#udp').val();
    $.ajax({
        dataType: 'json',
        url: '/api/'+obj+'/'+sn+'/'+server+' '+tcp+' '+udp,
        success: function (resp) {
			if (cb!=null)
				cb(resp);
			else
				$("#result_msg").text(resp.val);
        }, error: function (xhr) {
            console.log("Error on ajax call " + xhr);
			if (ecb!=null)
				ecb(xhr);
        }
    })
}

function plate_config_call(obj, cb, ecb) {
    var sn=$('#dev_sn').val();
	var plate_num=$('#plate_num').val();
    $.ajax({
        dataType: 'json',
        url: '/api/'+obj+'/'+sn+'/'+plate_num,
        success: function (resp) {
			if (cb!=null)
				cb(resp);
			else
				$("#result_msg").text(resp.val);
        }, error: function (xhr) {
            console.log("Error on ajax call " + xhr);
			if (ecb!=null)
				ecb(xhr);
        }
    })
}

function vin_config_call(obj, cb, ecb) {
    var sn=$('#dev_sn').val();
	var vin_num=$('#vin_num').val();
    $.ajax({
        dataType: 'json',
        url: '/api/'+obj+'/'+sn+'/'+vin_num,
        success: function (resp) {
			if (cb!=null)
				cb(resp);
			else
				$("#result_msg").text(resp.val);
        }, error: function (xhr) {
            console.log("Error on ajax call " + xhr);
			if (ecb!=null)
				ecb(xhr);
        }
    })
}

function speed_config_call(obj, cb, ecb) {
    var sn=$('#dev_sn').val();
	var speed=$('#speed').val();
    $.ajax({
        dataType: 'json',
        url: '/api/'+obj+'/'+sn+'/'+speed,
        success: function (resp) {
			if (cb!=null)
				cb(resp);
			else
				$("#result_msg").text(resp.val);
        }, error: function (xhr) {
            console.log("Error on ajax call " + xhr);
			if (ecb!=null)
				ecb(xhr);
        }
    })
}

function sim2_config_call(obj, cb, ecb) {
    var sn=$('#dev_sn').val();
	var sim=$('#sim').val();
    $.ajax({
        dataType: 'json',
        url: '/api/'+obj+'/'+sn+'/'+sim,
        success: function (resp) {
			if (cb!=null)
				cb(resp);
			else
				$("#result_msg").text(resp.val);
        }, error: function (xhr) {
            console.log("Error on ajax call " + xhr);
			if (ecb!=null)
				ecb(xhr);
        }
    })
}

function speed1_config_call(obj, cb, ecb) {
    var sn=$('#dev_sn').val();
	var speed=$('#speed').val();
    $.ajax({
        dataType: 'json',
        url: '/api/'+obj+'/'+sn+'/'+speed,
        success: function (resp) {
			if (cb!=null)
				cb(resp);
			else
				$("#result_msg").text(resp.val);
        }, error: function (xhr) {
            console.log("Error on ajax call " + xhr);
			if (ecb!=null)
				ecb(xhr);
        }
    })
}

function plate1_config_call(obj, cb, ecb) {
    var sn=$('#dev_sn').val();
	var plate1_num=$('#plate_num1').val();
	var plate2_num=$('#plate_num2').val();
    $.ajax({
        dataType: 'json',
        url: '/api/'+obj+'/'+sn+'/'+plate1_num+plate2_num,
        success: function (resp) {
			if (cb!=null)
				cb(resp);
			else
				$("#result_msg").text(resp.val);
        }, error: function (xhr) {
            console.log("Error on ajax call " + xhr);
			if (ecb!=null)
				ecb(xhr);
        }
    })
}

function sim1_config_call(obj, cb, ecb) {
	var sn=$('#dev_sn').val();
    var sim1=$('#sim1').val();
    $.ajax({
        dataType: 'json',
        url: '/api/'+obj+'/'+sn+'/'+sim1,
        success: function (resp) {
			if (cb!=null)
				cb(resp);
			else
				$("#result_msg").text(resp.val);
        }, error: function (xhr) {
            console.log("Error on ajax call " + xhr);
			if (ecb!=null)
				ecb(xhr);
        }
    })
}

function vin1_config_call(obj, cb, ecb) {
	var sn=$('#dev_sn').val();
    var vin1=$('#vin1').val();
    $.ajax({
        dataType: 'json',
        url: '/api/'+obj+'/'+sn+'/'+vin1,
        success: function (resp) {
			if (cb!=null)
				cb(resp);
			else
				$("#result_msg").text(resp.val);
        }, error: function (xhr) {
            console.log("Error on ajax call " + xhr);
			if (ecb!=null)
				ecb(xhr);
        }
    })
}

function color1_config_call(obj, cb, ecb) {
	var sn=$('#dev_sn').val();
    var color1=$('#color1').val();
    $.ajax({
        dataType: 'json',
        url: '/api/'+obj+'/'+sn+'/'+color1,
        success: function (resp) {
			if (cb!=null)
				cb(resp);
			else
				$("#result_msg").text(resp.val);
        }, error: function (xhr) {
            console.log("Error on ajax call " + xhr);
			if (ecb!=null)
				ecb(xhr);
        }
    })
}

function plate_color_config_call(obj, cb, ecb) {
    var sn=$('#dev_sn').val();
	var plate_color=$('#plate_color').val();
    $.ajax({
        dataType: 'json',
        url: '/api/'+obj+'/'+sn+'/'+plate_color,
        success: function (resp) {
			if (cb!=null)
				cb(resp);
			else
				$("#result_msg").text(resp.val);
        }, error: function (xhr) {
            console.log("Error on ajax call " + xhr);
			if (ecb!=null)
				ecb(xhr);
        }
    })
}

function mirror_server_call(obj, cb, ecb) {
    var sn=$('#dev_sn').val();
    var add_server=$('#add_server').val();
	var add_tcp=$('#add_tcp').val();
	var add_udp=$('#add_udp').val();
    $.ajax({
        dataType: 'json',
        url: '/api/'+obj+'/'+sn+'/'+add_server+' '+add_tcp+' '+add_udp,
        success: function (resp) {
			if (cb!=null)
				cb(resp);
			else
				$("#result_msg").text(resp.val);
        }, error: function (xhr) {
            console.log("Error on ajax call " + xhr);
			if (ecb!=null)
				ecb(xhr);
        }
    })
}

function del_mirror_server_call(obj, cb, ecb) {
    var sn=$('#dev_sn').val();
    var mirror_server=$('#del_server').val();
    $.ajax({
        dataType: 'json',
        url: '/api/'+obj+'/'+sn+'/'+mirror_server,
        success: function (resp) {
			if (cb!=null)
				cb(resp);
			else
				$("#result_msg").text(resp.val);
        }, error: function (xhr) {
            console.log("Error on ajax call " + xhr);
			if (ecb!=null)
				ecb(xhr);
        }
    })
}

//查询类
function dev_get_online() {
	common_call('online');
}
function dev_get_uptime() {
	common_call('get_uptime');
}
function dev_get_collect() {
	common_call('get_collect');
}
function dev_get_mount() {
	common_call('get_mount');
}
function dev_get_system_build() {
	common_call('get_system_build');
}
function dev_get_ps() {
	common_call('get_ps');
}
function dev_get_voltage() {
	common_call('get_voltage');
}
function dev_get_vdr_config() {
	common_call('get_vdr_config');
}
function dev_get_speed_limit() {
	common_call('get_speed_limit');
}
function dev_get_gps_signal() {
	common_call('get_gps_signal');
}
function dev_get_server_status() {
	common_call('get_server_status');
}
function dev_get_gpsinfo() {
	common_call('get_gpsinfo');
}
function dev_get_scinfo() {
	common_call('get_scinfo');
}
function dev_get_dumptime() {
	common_call('get_dumptime');
}
function dev_get_overtime() {
	common_call('get_overtime');
}
function dev_get_tts_vol() {
	common_call('get_tts_vol');
}
function dev_get_4g_version() {
	common_call('get_4g_version');
}
function dev_get_print_log() {
	common_call('get_print_log');
}
function dev_get_vdr0200() {
	common_call('get_vdr0200');
}
function dev_get_drive_time() {
	common_call('get_drive_time')
}
function dev_get_driver_list() {
	common_call('get_driver_list');
}
function dev_get_auth_status() {
	common_call('get_auth_status');
}
function dev_get_showflow() {
	common_call('get_showflow');
}
function dev_get_dhcp_status() {
	common_call('get_dhcp_status');
}
function dev_get_arp() {
	common_call('get_arp');
}
function dev_get_qos() {
	common_call('get_qos');
}
function dev_get_urlfilter() {
	common_call('get_urlfilter');
}
function dev_get_local_log() {
	common_call('get_local_log');
}
function dev_get_access_log() {
	common_call('get_access_log');
}
function dev_get_port_info() {
	common_call('get_port_info');
}
function dev_get_camera_ps() {
	common_call('get_camera_ps');
}
function dev_get_camera_ip() {
	common_call('get_camera_ip');
}
function dev_get_vdr9101() {
	common_call('get_vdr9101');
}

//操作类

function dev_opt_sysupgrade() {
	common_call('opt_sysupgrade');
}
function dev_opt_force_sysupgrade() {
	common_call('opt_force_sysupgrade');
}
function dev_opt_reboot() {
	common_call('opt_reboot');
}

function dev_opt_restart_vdr() {
	common_call('opt_restart_vdr');
}
function dev_opt_tts_test() {
	common_call('opt_tts_test');
}
function dev_opt_upvdr() {
	common_call('opt_upvdr');
}

function dev_opt_tts_vol_config() {
	common_call('opt_tts_vol_config');
}

function dev_opt_upvdr_beta() {
	common_call('opt_upvdr_beta');
}
function dev_opt_vdr_server_config() {
	server_call('opt_vdr_server_config');
}

function dev_opt_vdr1_plate_config() {
	plate1_config_call('opt_vdr1_plate_config');
}

function dev_opt_vdr_sim1_config() {
	sim1_config_call('opt_vdr_sim1_config');
}

function dev_opt_vdr_vin1_config() {
	vin1_config_call('opt_vdr_vin1_config');
}

function dev_opt_vdr_color1_config() {
	color1_config_call('opt_vdr_color1_config');
}

function dev_opt_vdr_plate_config() {
    plate_config_call('opt_vdr_plate_config');
}

function dev_opt_vdr_vin_config() {
    vin_config_call('opt_vdr_vin_config');
}

function dev_opt_vdr1_speed_config() {
    speed1_config_call('opt_vdr1_speed_config');
}

function dev_opt_vdr2_speed_config() {
    speed_config_call('opt_vdr2_speed_config');
}

function dev_opt_vdr2_sim_config() {
	sim2_config_call('opt_vdr2_sim_config');
}

function dev_opt_night_speed() {
	common_call('opt_vdr_night_speed');
}
function dev_opt_vdr_plate_color_config() {
    plate_color_config_call('opt_vdr_plate_color_config');
}

function dev_opt_add_mirror_config() {
	mirror_server_call('opt_add_mirror_config');
}
function dev_opt_del_mirror_config() {
	del_mirror_server_call('opt_del_mirror_config');
}
function dev_opt_del_backserver_config() {
	common_call('opt_del_backserver_config');
}
function dev_opt_vdr_log() {
	common_call('opt_vdr_log');
}
function dev_opt_overtime_config() {
	common_call('opt_overtime_config');
}
function dev_opt_speed_tts() {
	common_call('opt_speed_tts');
}
function dev_opt_speed_limit_tts() {
	common_call('opt_speed_limit_tts');
}
function dev_opt_simno_config() {
	common_call('opt_simno_config');
}
function dev_opt_private_config() {
	common_call('opt_private_config');
}
function dev_opt_speed_limit_config() {
	common_call('opt_speed_limit_config');
}
function dev_opt_tts_vol_config() {
	common_call('opt_tts_vol_config');
}
function dev_opt_print_test() {
	common_call('opt_print_test');
}
function dev_opt_4g_upgrade() {
	common_call('opt_4g_upgrade');
}
function dev_opt_url_filter() {
	common_call('opt_url_filter');
}
function dev_opt_itc_limit() {
	common_call('opt_itc_limit');
}
function dev_opt_repair_ssd() {
	common_call('opt_repair_ssd');
}
function dev_opt_tiny_web() {
	common_call('opt_tiny_web');
}
function dev_opt_web_file() {
	common_call('opt_web_file');
}
function dev_opt_php_config() {
	common_call('opt_php_config');
}
function dev_opt_update_init() {
	common_call('opt_update_init');
}
function dev_opt_update_host() {
	common_call('opt_update_host');
}
function dev_opt_reboot_camera_ps() {
	common_call('opt_reboot_camera_ps');
}
function dev_opt_port_switch() {
	common_call('opt_port_switch');
}
function dev_opt_gateway_config() {
	common_call('opt_gateway_config');
}

function exe_cmd() {
	cmd_call('opt_exe_cmd')
}


//打开SSH终端
function device_console(){
	common_call('term', function(resp){
		set_tunn_cookie("TUNN_SEED",resp.val);
		var url=window.location.origin+'/tun/'+resp.val+'/';
		window.open(url);
	}, function(xhr){
		alert("Error open console");
	});
}

//打开Portal1
function device_web(){
	common_call('web', function(resp){
		set_tunn_cookie("TUNN_SEED",resp.val);
		var url=window.location.origin+'/tun/'+resp.val+'/';
		window.open(url);
	}, function(xhr){
		alert("Error open console");
	});
}

//打开Portal2
function device_web2(){
	common_call('web2', function(resp){
		set_tunn_cookie("TUNN_SEED",resp.val);
		window.open(window.location.origin+'/xtun');
	}, function(xhr){
		alert("Error open console");
	});
}
//pro_test
function pro_test() {
    console.log("pro_test1");
    pre_result =$("#pro_data").val(); //获取用户输入 7e800100050130070661730000166b020000d97e
    console.log("pro_test2\n"+pre_result); //打印用户输入
    pre_result=pre_data(pre_result); //数据预处理,
    console.log("pro_test3\n"+pre_result);
    protocolid=pre_result.substring(2,6); //消息ID为第2~6Bit
	console.log("MessageID:"+protocolid);
    pro_test_call(protocolid);
}

function pro_test_call(obj, cb, ecb) { //协议解析
    //var pro_data=$('#pro_data').val();
    var pro_data =pre_result;
    $.ajax({
        dataType: 'json',
        url: '/api/'+obj+'/'+pro_data, //http://0.0.0.0/api/8001/7e800100050130070661730000166b020000d97e
        success: function (resp) {
			if (cb!=null)
				cb(resp);
			else
                //console.log("resp.val"+resp.val)
                //console.log(typeof(resp))
                //var str = JSON.stringify(resp)
                //console.log(typeof(str))
                //console.log(str)
                //str=str.replace(/,/g, "_ ")
                //console.log(str)
                //var obj = JSON.parse(str);
                //console.log(typeof(obj))
				$("#analyse_result").text(resp.val);
        }, error: function (xhr) {
            console.log("Error on ajax call " + xhr);
			if (ecb!=null)
				ecb(xhr);
        }
    })
}
function pre_data(data){
    console.log("pre_data\n"+data);
    function StringBuffer() {
            this.__strings__ = [];
        };
        StringBuffer.prototype.append = function(str) {
            this.__strings__.push(str);
        };
        StringBuffer.prototype.toString = function() {
            return this.__strings__.join('');
        };
            //$('#analyse_data').click(function () {
                var cbuffer = new StringBuffer();//声明一个对象
                var contents= new Array();
                var contents_tmp= new Array();
                var prodatastr="";
                //contents = $("#pro_data").val().split("\n");
                contents = data.split("\n");
                console.log("pre_data Type:"+typeof(contents));
                if (contents.indexOf("|") != -1 ){
                    for (i=0;i<contents.length ;i++ )
                    {
                        console.log(i,contents[i]); //分割后的字符输出
                        var strStartIndex = contents[i].indexOf(":");
                        var strEndIndex = contents[i].indexOf("|");
                        if(strStartIndex < 0 && strEndIndex < 0){
                            console.log("没有：也没有|");
                            cbuffer.append(contents[i].substring(0, contents[i].length));
                        }else if(strStartIndex < 0 && strEndIndex > 0){
                            console.log("没有：");
                            cbuffer.append(contents[i].substring(0, strEndIndex));
                        }else if(strEndIndex < 0 && strStartIndex > 0){
                            console.log("没有|");
                            cbuffer.append(contents[i].substring(strStartIndex+2, contents[i].length));
                        }else{
                            console.log("正常");
                            cbuffer.append(contents[i].substring(strStartIndex+2, strEndIndex));
                        }
                    }
                }
                else{
                    for (i=0;i<contents.length ;i++ )
                    {
                        console.log(i,contents[i]); //分割后的字符输出
                        var strEndIndex = contents[i].indexOf("  ");
                        if(strEndIndex > 0){
                            contents_tmp[i]=contents[i].substring(0, strEndIndex);
                            var strStartIndex = contents_tmp[i].lastIndexOf(":");
                            if(strStartIndex > 0){
                                cbuffer.append(contents_tmp[i].substring(strStartIndex+2, strEndIndex));
                            }
                            else{
                                cbuffer.append(contents_tmp[i].substring(0, strEndIndex));
                            }
                        }
                        else{
                            var strStartIndex = contents[i].lastIndexOf(":");
                            if(strStartIndex > 0){
                                cbuffer.append(contents[i].substring(strStartIndex+2, contents[i].length));
                            }
                            else{
                                cbuffer.append(contents[i].substring(0, contents[i].length));
                            }
                        }
                    }
                }
                prodatastr = cbuffer.toString();
                console.log("prodatastr:\n"+prodatastr);
                var dest = "";
                if (prodatastr.length != 0){
                    dest=prodatastr.replace(/(^[\s\n\t]+|[\s\n\t]+$)/g, "");
                    dest=dest.replace(/\s+/g, "");
                    dest = dest.replace("7d02", "7e");
                    dest = dest.replace("7d01", "7d"); //必要的替换/转义操作
                    prodatastr = dest;
                    console.log("ReplaceResult:\n"+prodatastr);
                    return prodatastr;
                }
           // });
}

//upload
function upload_file() {
    console.log("upload");
    abs_filename =$("#File1").val(); //获取上传的文件名
    console.log("abs_filename\n"+abs_filename)
    var pos=abs_filename.lastIndexOf("\\");//最后一个\出现的位置
    console.log("pos\n"+pos)
    filename=abs_filename.substring(pos+1)
    console.log("filename\n"+filename); //打印文件名
    upload_call("upload");
}

function upload_call(obj, cb, ecb) {
    var filname =filename;
    $.ajax({
        dataType: 'json',
        url: '/api/'+obj+'/'+filename, //http://0.0.0.0/api/upload/filename
        success: function (resp) {
            if (cb!=null)
                cb(resp);
            else
                console.log("resp.val"+resp.val)
                //console.log(typeof(resp))
                //var str = JSON.stringify(resp)
                //console.log(typeof(str))
                //console.log(str)
                //str=str.replace(/,/g, "_ ")
                //console.log(str)
                //var obj = JSON.parse(str);
                //console.log(typeof(obj))
                //$("#analyse_result").text(resp.val);
        }, error: function (xhr) {
            console.log("Error on ajax call " + xhr);
            if (ecb!=null)
                ecb(xhr);
        }
    })
}

function ajaxForm(){
        var form= new FormData(document.getElementById("test_form"));
        $.ajax({
            //url:"{{ url_for('api_upload') }}",
            url:"/api/up_photo",
            type:"post",
            data:form,
            dataType: 'json',
            processData:false,
            contentType:false,
            success:function(data){
                   // $(img_url_new).attr("src",data.img_url_new);
                   // $(imgPic).attr("src",data.img_url_new);
                   console.log("upload success")
            },
            error:function(e){
                    alert("error");
            }
        })
}

function clear_input() {
    console.log("clear_input");
    input_value=$("#pro_data").val();
    if (input_value !=""){
    

  var txtclean=   document.getElementById("pro_data");
txtclean.value="";
    }
}
